#!/bin/bash

ospkg_source_china()
{
	# https://mirrors.ustc.edu.cn/help/debian.html
	# https://mirrors.ustc.edu.cn/help/ubuntu.html
	local mirror_site=mirrors.163.com
	local mirror_site=mirrors.ustc.edu.cn
	$SUDO sed -i -e "s/deb.debian.org/$mirror_site/g" \
		     -e "s/archive.ubuntu.com/$mirror_site/g" \
		     -e "s/security.ubuntu.com/$mirror_site/g" \
		     -e "s|security.debian.org/debian-security|mirrors.ustc.edu.cn/debian-security|g" \
		     /etc/apt/sources.list

	# extra debian repos
	$SUDO sed -i -e 's/ main$/ main contrib non-free/' \
			/etc/apt/sources.list
}

ospkg_update()
{
	ospkg_source_china

	$SUDO apt-get -q update
}

ospkg_install()
{
	# chronic is provided by deps/pack.cgz, but nfs rootfs + run_on_local_disk environment,
	# deps/pack.cgz will not be merged into the runtime rootfs currently.
	# one by one installation improve the installation success rate.
	if has_cmd chronic; then
		chronic=chronic
	else
		chronic=
	fi

	local err=
	local tmp_output=/tmp/apt-get.output.lkp.$USER

	for package
	do
		$SUDO $chronic apt-get -o Dpkg::Options::=--force-confdef \
				 -o Dpkg::Options::=--force-confold \
				 install -q -y --no-upgrade --no-install-recommends $package > $tmp_output 2>&1 || err=$?
		grep -v "dpkg: warning: files list file for package '.*' missing;"  $tmp_output
	done
	rm  $tmp_output

	return $err
}

ospkg_list()
{
	apt list 2>/dev/null | awk -F/ '/\// { print $1 }' |
		grep -v '\-doc$' | sort -u
}
